package com.example.myapplication.flow

import androidx.lifecycle.*
import com.orhanobut.logger.Logger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class FlowLIvedata0913 : ViewModel() {

    val foo: LiveData<Int> = liveData {
        flowOf(1, 23)
            .onStart {
                uistate.value = false
                /* emit loading state */
            }
            .onCompletion {
                uistate.value = true
            }
            .catch { exception -> /* emit error state */ }
            .collect {
                emit(it)
            }
    }

    var foo2 = flowOf(1, 2).asLiveData()

    suspend fun getfloe() = flow {
        emit(1)
        emit(12)
        ui2.emit(14)

    }

    fun t2() {
    }

    private val uistate = MutableStateFlow<Boolean>(false)
    val uistate2 = uistate.asStateFlow()

    fun ttt1() {
        var shaoe: Flow<Int> = uistate.flatMapLatest {
            flowOf(1)
        }
    }


    private val ui2 = MutableSharedFlow<Int>()

    var pui2 = ui2.asSharedFlow()


    //    在一般的flow在构造代码块中不允许切换线程，ChannelFlow则允许内部切换线程
    val channelFolw = channelFlow<String> {
        send("1")
        withContext(Dispatchers.IO) {
            send("io")
        }
    }
    val callbackflow = callbackFlow<String> {
        send("1")
        withContext(Dispatchers.IO) {
            send("callbackflow")
        }
        awaitClose {
            Logger.d("FlowLIvedata0913===: awaitClose=");

        }

    }

    fun t1() {
        viewModelScope.launch {
            channelFolw.collect {
                Logger.d("FlowLIvedata0913===t1: it==" + it);

            }

        }
    }
}